import { initParticlesJS } from '../particles.js'

// 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            //粒子效果
            initParticlesJS();
            // 检查用户登录状态并更新界面
            updateUserInterface();

            // 加载商品数据
            loadProducts();

            // 设置交互功能
            setupInteractions();

            // 设置分类按钮功能
            setupCategoryButtons();

            // 设置规格按钮功能
            setupSpecButtons();

            // 设置数量控制功能
            setupQuantityControls();

            // 设置正在开发中的功能
            setupDevelopmentFeatures();

            // 移动菜单切换
            document.getElementById('mobile-menu-btn').addEventListener('click', function() {
                const mobileMenu = document.getElementById('mobile-menu');
                if (mobileMenu.classList.contains('hidden')) {
                    mobileMenu.classList.remove('hidden');
                } else {
                    mobileMenu.classList.add('hidden');
                }
            });
        });

        // 更新用户界面
        function updateUserInterface() {
            const user = localStorage.getItem('currentUser') ? JSON.parse(localStorage.getItem('currentUser')) : null;
            const authSection = document.getElementById('user-auth-section');
            const infoSection = document.getElementById('user-info-section');
            
            if (user) {
                authSection.classList.add('hidden');
                infoSection.classList.remove('hidden');
                document.getElementById('username').textContent = user.username;
                document.getElementById('user-avatar').src = user.avatar || 'https://picsum.photos/40/40';

                // 退出登录
                document.getElementById('logout-btn').addEventListener('click', function() {
                    localStorage.removeItem('currentUser');
                    window.location.reload();
                });
            } else {
                authSection.classList.remove('hidden');
                infoSection.classList.add('hidden');
            }

            // 更新购物车数量
            updateCartCount();
        }

        // 更新购物车数量
        function updateCartCount() {
            const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
            const cartCount = document.getElementById('cart-count');
            cartCount.textContent = cart.length;
        }

        // 加载商品数据
        function loadProducts() {
            // 模拟商品数据，实际应用中应从服务器获取
            const products = [
                {
                    id: 1,
                    name: '专业碳素鱼竿',
                    price: 299,
                    originalPrice: 399,
                    image: 'https://picsum.photos/400/300?rod',
                    category: 'rods',
                    featured: true,
                    hot: true,
                    description: '超轻超硬碳素材质，28调节多功能鱼竿，适合各种钓鱼场景，手感舒适，性能稳定。长度可选范围：3.6米-7.2米，搭配优质渔轮效果更佳。'
                },
                {
                    id: 2,
                    name: '金属轴承渔轮',
                    price: 199,
                    originalPrice: 259,
                    image: 'https://picsum.photos/400/300?reel',
                    category: 'reels',
                    featured: true,
                    hot: true,
                    description: '12+1轴承设计，超强耐磨金属材质，高速比5.2:1，轻松应对大鱼。配备精准刹车系统，可调节松紧度，适合各种钓鱼环境。'
                },
                {
                    id: 3,
                    name: '仿生软饵套装',
                    price: 89,
                    originalPrice: 119,
                    image: 'https://picsum.photos/400/300?bait',
                    category: 'lures',
                    featured: true,
                    hot: false,
                    description: '30款多彩软饵，高度仿真设计，柔软有弹性，气味持久。适合淡水和海水环境，针对不同鱼种有特殊配方，效果显著。'
                },
                {
                    id: 4,
                    name: '多功能钓箱',
                    price: 359,
                    originalPrice: 459,
                    image: 'https://picsum.photos/400/300?box',
                    category: 'accessories',
                    featured: true,
                    hot: true,
                    description: '高强度工程塑料材质，多层设计，大容量储物空间。内置可调节隔板，防水防潮，配备舒适坐垫和便携把手，户外钓鱼必备装备。'
                },
                {
                    id: 5,
                    name: '高强度鱼线',
                    price: 45,
                    originalPrice: 65,
                    image: 'https://picsum.photos/400/300?line',
                    category: 'lines',
                    featured: false,
                    hot: true,
                    description: '日本进口材料，高强度低延展性，抗磨损抗腐蚀，几乎零记忆力。500米长度，多种规格可选，适合各种钓法和鱼种。'
                },
                {
                    id: 6,
                    name: '专业钓鱼服装套装',
                    price: 299,
                    originalPrice: 399,
                    image: 'https://picsum.photos/400/300?clothing',
                    category: 'clothing',
                    featured: false,
                    hot: true,
                    description: '速干透气面料，防晒防水，多口袋设计方便存放小物件。可拆卸袖子和裤腿，适应不同天气环境，户外活动的理想选择。'
                },
                {
                    id: 7,
                    name: '高级碳素短节鱼竿',
                    price: 599,
                    originalPrice: 799,
                    image: 'https://picsum.photos/400/300?rod2',
                    category: 'rods',
                    featured: false,
                    hot: false,
                    description: '采用日本东丽碳素纤维，高强度轻量化设计，短节便携，方便携带。快速反应，手感灵敏，适合路亚钓法和竞技钓鱼。'
                },
                {
                    id: 8,
                    name: '精致鱼钩套装',
                    price: 69,
                    originalPrice: 99,
                    image: 'https://picsum.photos/400/300?hook',
                    category: 'hooks',
                    featured: false,
                    hot: false,
                    description: '100枚装，10种规格，高碳钢材质，经久耐用不易生锈。锋利的钩尖，高穿透力，钓获率提升30%，适合各种鱼类。'
                }
            ];

            // 显示精选商品
            const featuredProducts = products.filter(product => product.featured);
            displayProducts(featuredProducts, 'featured-products');

            // 显示热销商品
            const hotProducts = products.filter(product => product.hot);
            displayProducts(hotProducts, 'hot-products');

            // 显示所有商品
            displayProducts(products, 'all-products');

            // 保存商品数据到localStorage，用于其他页面使用
            localStorage.setItem('products', JSON.stringify(products));
        }

        // 显示商品
        function displayProducts(products, containerId) {
            const container = document.getElementById(containerId);
            container.innerHTML = '';

            products.forEach(product => {
                const productElement = document.createElement('div');
                productElement.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition duration-300 transform hover:-translate-y-1';
                productElement.innerHTML = `
                    <div class="relative">
                        <img src="${product.image}" alt="${product.name}" class="w-full h-48 object-cover cursor-pointer product-image" data-id="${product.id}">
                        ${product.hot ? '<span class="absolute top-2 right-2 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded">热销</span>' : ''}
                    </div>
                    <div class="p-4">
                        <h3 class="font-bold text-lg mb-1 cursor-pointer product-name" data-id="${product.id}">${product.name}</h3>
                        <div class="flex items-center mb-2">
                            <div class="flex text-yellow-400 text-sm mr-1">
                                <i class="fas fa-star"></i>
                                <i class="fas fa-star"></i>
                                <i class="fas fa-star"></i>
                                <i class="fas fa-star"></i>
                                <i class="fas fa-star-half-alt"></i>
                            </div>
                            <span class="text-xs text-gray-500">(${Math.floor(Math.random() * 200) + 50})</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <div>
                                <span class="text-red-600 font-bold">¥${product.price}.00</span>
                                <span class="text-gray-500 text-sm line-through ml-1">¥${product.originalPrice}.00</span>
                            </div>
                            <button class="add-to-cart bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm transition duration-300" data-id="${product.id}">
                                加入购物车
                            </button>
                        </div>
                    </div>
                `;
                container.appendChild(productElement);
            });

            // 添加商品点击事件
            const productImages = container.querySelectorAll('.product-image');
            const productNames = container.querySelectorAll('.product-name');
            
            productImages.forEach(image => {
                image.addEventListener('click', function() {
                    const productId = this.getAttribute('data-id');
                    openProductModal(productId);
                });
            });
            
            productNames.forEach(name => {
                name.addEventListener('click', function() {
                    const productId = this.getAttribute('data-id');
                    openProductModal(productId);
                });
            });

            // 添加购物车按钮点击事件
            const addToCartButtons = container.querySelectorAll('.add-to-cart');
            addToCartButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const productId = this.getAttribute('data-id');
                    addToCart(productId, 1);
                });
            });
        }

        // 打开商品详情模态框
        function openProductModal(productId) {
            const products = JSON.parse(localStorage.getItem('products'));
            const product = products.find(p => p.id === parseInt(productId));
            
            if (product) {
                document.getElementById('modal-product-image').src = product.image;
                document.getElementById('modal-product-name').textContent = product.name;
                document.getElementById('modal-product-price').textContent = `¥${product.price}.00`;
                document.getElementById('modal-product-desc').textContent = product.description;
                document.getElementById('product-quantity').value = 1;
                
                // 设置添加到购物车按钮的data属性
                document.getElementById('add-to-cart-modal').setAttribute('data-id', product.id);
                
                // 显示模态框
                document.getElementById('product-modal').classList.remove('hidden');
            }
        }

        // 添加到购物车
        function addToCart(productId, quantity) {
            const products = JSON.parse(localStorage.getItem('products'));
            const product = products.find(p => p.id === parseInt(productId));
            
            if (product) {
                // 获取当前购物车
                let cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
                
                // 检查商品是否已在购物车中
                const existingItemIndex = cart.findIndex(item => item.id === product.id);
                
                if (existingItemIndex !== -1) {
                    // 更新数量
                    cart[existingItemIndex].quantity += parseInt(quantity);
                } else {
                    // 添加新商品
                    cart.push({
                        id: product.id,
                        name: product.name,
                        price: product.price,
                        image: product.image,
                        quantity: parseInt(quantity)
                    });
                }
                
                // 保存购物车
                localStorage.setItem('cart', JSON.stringify(cart));
                
                // 更新购物车数量
                updateCartCount();
                
                // 更新购物车侧边栏
                updateCartSidebar();
                
                // 显示通知
                showNotification('已添加商品到购物车');
                
                // 关闭产品模态框（如果打开的话）
                document.getElementById('product-modal').classList.add('hidden');
                
                // 打开购物车侧边栏
                document.getElementById('cart-sidebar').classList.remove('translate-x-full');
            }
        }

        // 更新购物车侧边栏
        function updateCartSidebar() {
            const cartItems = document.getElementById('cart-items');
            const cartTotal = document.getElementById('cart-total');
            const cart = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
            
            if (cart.length === 0) {
                cartItems.innerHTML = `
                    <div class="text-center text-gray-500 py-10">
                        <i class="fas fa-shopping-cart text-5xl mb-3"></i>
                        <p>您的购物车是空的</p>
                    </div>
                `;
                cartTotal.textContent = '¥0.00';
                return;
            }
            
            let totalPrice = 0;
            cartItems.innerHTML = '';
            
            cart.forEach(item => {
                const itemTotal = item.price * item.quantity;
                totalPrice += itemTotal;
                
                const itemElement = document.createElement('div');
                itemElement.className = 'flex items-start border-b border-gray-200 pb-4 mb-4';
                itemElement.innerHTML = `
                    <img src="${item.image}" alt="${item.name}" class="w-16 h-16 object-cover rounded mr-3">
                    <div class="flex-1">
                        <h4 class="font-medium">${item.name}</h4>
                        <div class="flex justify-between mt-1">
                            <span class="text-gray-600">¥${item.price} × ${item.quantity}</span>
                            <span class="font-medium">¥${itemTotal.toFixed(2)}</span>
                        </div>
                    </div>
                    <button class="remove-from-cart ml-2 text-gray-400 hover:text-red-500" data-id="${item.id}">
                        <i class="fas fa-trash"></i>
                    </button>
                `;
                cartItems.appendChild(itemElement);
            });
            
            // 添加移除商品事件
            const removeButtons = cartItems.querySelectorAll('.remove-from-cart');
            removeButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const productId = parseInt(this.getAttribute('data-id'));
                    removeFromCart(productId);
                });
            });
            
            // 更新总价
            cartTotal.textContent = `¥${totalPrice.toFixed(2)}`;
        }

        // 从购物车移除商品
        function removeFromCart(productId) {
            let cart = JSON.parse(localStorage.getItem('cart') || '[]');
            cart = cart.filter(item => item.id !== productId);
            localStorage.setItem('cart', JSON.stringify(cart));
            
            // 更新购物车数量
            updateCartCount();
            
            // 更新购物车侧边栏
            updateCartSidebar();
            
            // 显示通知
            showNotification('已从购物车移除商品');
        }

        // 设置交互功能
        function setupInteractions() {
            // 商品模态框关闭按钮
            document.getElementById('close-product-modal').addEventListener('click', function() {
                document.getElementById('product-modal').classList.add('hidden');
            });

            // 商品模态框中的加入购物车按钮
            document.getElementById('add-to-cart-modal').addEventListener('click', function() {
                const productId = this.getAttribute('data-id');
                const quantity = document.getElementById('product-quantity').value;
                addToCart(productId, quantity);
            });

            // 立即购买按钮
            document.getElementById('buy-now').addEventListener('click', function() {
                const productId = document.getElementById('add-to-cart-modal').getAttribute('data-id');
                const quantity = document.getElementById('product-quantity').value;
                addToCart(productId, quantity);
                // 跳转到购物车页面
                window.location.href = 'cart.html';
            });

            // 购物车侧边栏关闭按钮
            document.getElementById('close-cart-sidebar').addEventListener('click', function() {
                document.getElementById('cart-sidebar').classList.add('translate-x-full');
            });

            // 点击购物车图标打开侧边栏
            document.querySelector('a[href="cart.html"]').addEventListener('click', function(e) {
                e.preventDefault();
                updateCartSidebar();
                document.getElementById('cart-sidebar').classList.remove('translate-x-full');
            });

            // 排序选择功能
            document.getElementById('sort-order').addEventListener('change', function() {
                // 实际应用中应该根据选择重新排序并显示商品
                showNotification('排序功能开发中，敬请期待！');
            });

            // 搜索功能
            document.getElementById('search-btn').addEventListener('click', function() {
                const searchTerm = document.getElementById('search-products').value.trim();
                if (searchTerm) {
                    // 实际应用中应该根据搜索词过滤并显示商品
                    showNotification('搜索功能开发中，敬请期待！');
                }
            });

            // 回车搜索
            document.getElementById('search-products').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('search-btn').click();
                }
            });
        }

        // 设置分类按钮功能
        function setupCategoryButtons() {
            const categoryButtons = document.querySelectorAll('.category-btn');
            
            categoryButtons.forEach(button => {
                button.addEventListener('click', function(e) {
                    e.preventDefault();
                    
                    // 移除所有按钮的active样式
                    categoryButtons.forEach(btn => {
                        btn.classList.remove('active', 'bg-blue-500', 'text-white');
                        btn.classList.add('bg-gray-200', 'text-gray-700');
                    });
                    
                    // 添加当前按钮的active样式
                    this.classList.remove('bg-gray-200', 'text-gray-700');
                    this.classList.add('active', 'bg-blue-500', 'text-white');
                    
                    const category = this.getAttribute('data-category');
                    
                    // 根据分类筛选商品
                    filterProductsByCategory(category);
                });
            });
        }

        // 根据分类筛选商品
        function filterProductsByCategory(category) {
            const products = JSON.parse(localStorage.getItem('products') || '[]');
            let filteredProducts;
            
            if (category === 'all') {
                filteredProducts = products;
            } else {
                filteredProducts = products.filter(product => product.category === category);
            }
            
            // 显示筛选后的商品
            displayProducts(filteredProducts, 'all-products');
        }

        // 设置规格按钮功能
        function setupSpecButtons() {
            const specButtons = document.querySelectorAll('.spec-btn');
            
            specButtons.forEach(button => {
                button.addEventListener('click', function() {
                    // 移除所有按钮的active样式
                    specButtons.forEach(btn => {
                        btn.classList.remove('active', 'border-blue-500', 'bg-blue-50', 'text-blue-600');
                        btn.classList.add('border-gray-300', 'hover:border-blue-500', 'hover:bg-blue-50', 'hover:text-blue-600');
                    });
                    
                    // 添加当前按钮的active样式
                    this.classList.remove('border-gray-300', 'hover:border-blue-500', 'hover:bg-blue-50', 'hover:text-blue-600');
                    this.classList.add('active', 'border-blue-500', 'bg-blue-50', 'text-blue-600');
                });
            });
        }

        // 设置数量控制功能
        function setupQuantityControls() {
            const decreaseBtn = document.getElementById('decrease-quantity');
            const increaseBtn = document.getElementById('increase-quantity');
            const quantityInput = document.getElementById('product-quantity');
            
            decreaseBtn.addEventListener('click', function() {
                let quantity = parseInt(quantityInput.value);
                if (quantity > 1) {
                    quantityInput.value = quantity - 1;
                }
            });
            
            increaseBtn.addEventListener('click', function() {
                let quantity = parseInt(quantityInput.value);
                quantityInput.value = quantity + 1;
            });
            
            quantityInput.addEventListener('change', function() {
                let quantity = parseInt(this.value);
                if (isNaN(quantity) || quantity < 1) {
                    this.value = 1;
                }
            });
        }

        // 设置正在开发中的功能
        function setupDevelopmentFeatures() {
            const devFeatureButtons = [
                document.getElementById('communityBtn'),
                document.getElementById('techniqueBtn')
            ];
            
            const devModal = document.getElementById('development-modal');
            const closeDevModal = document.getElementById('close-dev-modal');
            
            devFeatureButtons.forEach(button => {
                if (button) {
                    button.addEventListener('click', function(e) {
                        e.preventDefault();
                        devModal.classList.remove('hidden');
                    });
                }
            });
            
            closeDevModal.addEventListener('click', function() {
                devModal.classList.add('hidden');
            });
        }

        // 显示通知
        function showNotification(message) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.classList.remove('hidden');
            notification.classList.remove('translate-y-20', 'opacity-0');
            
            setTimeout(() => {
                notification.classList.add('translate-y-20', 'opacity-0');
                setTimeout(() => {
                    notification.classList.add('hidden');
                }, 300);
            }, 2000);
        }